<?php
/**
 * @Name  : AuthServices.php
 * @Author: yashuai
 */

namespace App\Http\Logic\Rbac;

use Firebase\JWT\JWT;
use App\Http\Model\ConstCode;
use App\Http\Logic\BaseLogic;
use App\Http\Model\Rbac\NodeModel;

class UserTokenLogic extends BaseLogic
{

    /**
     * @Desc   获取用户id
     * @param string $token
     * @return array|boolean
     * @throws \Exception
     * @author yashuai
     * @Time   2020/6/5 20:36
     */
    public function id($token = '')
    {
        if (empty($token)) {
            return false;
        }
        $jwtData = $this->decodeToken($token);
        if (empty($jwtData)) {
            return false;
        }

        if (empty($jwtData->jti) || empty($jwtData->userId) || $jwtData->jti != md5($jwtData->userId . $jwtData->iat)) {
            return false;
        }

        return $jwtData->userId;
    }

    /**
     * @Desc   生成用户Token
     * @param int $userId
     * @return string
     * @author yashuai
     * @Time   2020/6/23 16:28
     */
    public function createToken($userId = 0)
    {
        $newTime = time();
        $jti     = md5($userId . $newTime);
        $payload = array(
            "iat"    => $newTime,
            'jti'    => $jti,
            'userId' => $userId,
        );

        return JWT::encode($payload, env("AUTH_CODE", '0000'), 'HS256');
    }

    /**
     * @Desc   验证用户菜单权限
     *         注：关联权限为 实际的控制器名 实际方法名，不是路由路径
     * @return bool
     * @author yashuai
     */
    public function validatorNodePower()
    {
        if ($this->params['User']['IsSuper'] == ConstCode::IS_YES) {
            return true;
        }
        $data = [
            'user.menunode'   => 'allow',
            'user.info'        => 'allow',
            'department.index' => ['staff.index'],
            'user.create'      => ['role.map'],
            'user.update'      => ['role.map'],
            'role.node'        => ['node.index'],
            'staff.relation'   => [
                'staff.relationuserlist',
                'staff.relationnewuser',
                'staff.relationtableuser',
                'role.map'
            ],
        ];
        // 在关联权限中设置权限
        if (_array_field($data, $this->params['Event']) == 'allow') {
            return true;
        }
        // 在数据库内设置权限
        $joinSub  = NodeModel::getUserNodeIDArray($this->params['UserID']);
        $nodeList = NodeModel::query()->whereIn('NodeID', $joinSub)->pluck('EventType')->toArray();
        $return   = false;
        if (in_array($this->params['Event'], $nodeList)) {
            return true;
        } else {
            foreach ($data as $key => $node) {
                if (is_array($node) && in_array($this->params['Event'], $node) && in_array($key, $nodeList)) {
                    $return = true;
                    break;
                }
            }
        }
        return $return;
    }

    /**
     * @Desc   解密token
     * @param $token
     * @return bool|object|null
     * @author yashuai
     * @Time   2020/6/5 20:28
     */
    protected function decodeToken($token)
    {
        try {
            return JWT::decode($token, env("AUTH_CODE", '0000'), ['HS256']);
        } catch (\Exception $e) {
            return false;
        }
    }


}
